import React, { lazy, Suspense, useState, useCallback } from 'react';
import { Box } from '@mui/material';
import { AppHeader } from './AppHeader';
import { Sidebar } from './Sidebar';
import { FlowCanvas } from './FlowCanvas';
import { useFlowStore } from '../../store/flowStore';
import { useUIStore } from '../../store/uiStore';

// 懒加载非关键组件
const PropertiesPanel = lazy(() => import('../PropertiesPanel'));
const SettingsPanel = lazy(() => import('../SettingsPanel'));
const ProblemsPanel = lazy(() => import('../ProblemsPanel'));

/**
 * 行为树编辑器的主要内容组件
 * 组合了 AppHeader、Sidebar、FlowCanvas 和懒加载的面板组件
 */
export const FlowEditorContent: React.FC = () => {
  const { selectedNodeId, setSelectedNodeId } = useFlowStore();
  const { activeRightPanel, setActiveRightPanel } = useUIStore();
  const [isProblemsPanelOpen, setIsProblemsPanelOpen] = useState(false);

  // 面板显示逻辑
  const isPropertiesPanelOpen = activeRightPanel === 'properties' && !!selectedNodeId;
  const isSettingsPanelOpen = activeRightPanel === 'settings';

  // 使用useCallback优化回调函数
  const handlePropertiesPanelClose = useCallback(() => {
    setActiveRightPanel('settings');
  }, [setActiveRightPanel]);

  const handleSettingsPanelClose = useCallback(() => {
    setActiveRightPanel('properties');
  }, [setActiveRightPanel]);

  const handleProblemsPanelClose = useCallback(() => {
    setIsProblemsPanelOpen(false);
  }, []);

  return (
    <Box sx={{ display: 'flex', height: '100vh' }}>
      <AppHeader onProblemsPanelToggle={setIsProblemsPanelOpen} />
      <Sidebar />
      <FlowCanvas />
      {/* 使用 Suspense 包裹懒加载组件 */}
      <Suspense fallback={null}>
        <PropertiesPanel
          open={isPropertiesPanelOpen}
          onClose={handlePropertiesPanelClose}
          selectedNodeId={selectedNodeId}
        />
        <SettingsPanel
          open={isSettingsPanelOpen}
          onClose={handleSettingsPanelClose}
        />
        <ProblemsPanel
          open={isProblemsPanelOpen}
          onClose={handleProblemsPanelClose}
        />
      </Suspense>
    </Box>
  );
};